//多任务进入线程池的运行

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

class MyThreadPoolExecutor{
    //创建一个线程池
    private List<Thread> threadList = new ArrayList<>();
    //建立一个可以存储任务的队列
    private BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(1000);
    //将任务添加到队列里面去
    public void submit(Runnable runnable) throws InterruptedException {
        queue.put(runnable);
    }
    //通过n来指定创建线程的数量
    public MyThreadPoolExecutor(int n){
        for (int i = 0; i < n; i++) {
            Thread thread = new Thread(()->{
               while (true){
                   try {
                       //该线程要做的事情就是要把任务队列中的任务不停的取出来并执行
                       //take本身带有阻塞功能，若队列为空则直接阻塞
                       Runnable runnable = queue.take();
                       runnable.run();
                   } catch (InterruptedException e) {
                       throw new RuntimeException(e);
                   }
               }
            });
            thread.start();
            //将线程加入线程池中
            threadList.add(thread);
        }
    }
}
public class ThreadDemo30 {
    public static void main(String[] args) throws InterruptedException {
        MyThreadPoolExecutor myThreadPoolExecutor = new MyThreadPoolExecutor(4);
        for (int i = 0; i < 1000; i++) {
            int n = i;
            myThreadPoolExecutor.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("执行任务"+ n + ",当前线程为"+Thread.currentThread().getName());
                }
            });
        }
    }
}
